package com.rui1024.dao.impl;

import com.rui1024.dao.OrderDao;
import com.rui1024.pojo.Order;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.sql.Date;
import java.util.List;

public class OrderDaoImpl implements OrderDao {




    public List<Order> getAllOrder(Connection con) throws Exception{
        String sql = "select orderId,foodId,name,amount,orderTime from orders,menu where orders.foodId = menu.id";
        List<Order> list = new ArrayList<Order>();
        PreparedStatement pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        int amountCount=0;
        // 处理结果集
        while (rs.next()) {
            int orderId = rs.getInt("orderId");
            int foodId = rs.getInt("foodId");
            String foodName = rs.getString("name");
            int amount = rs.getInt("amount");
            Date orderTime = rs.getDate("orderTime");
            list.add(new Order(orderId, foodId, foodName, amount, orderTime));
        }
        return list;
    }
    public boolean order(int menuId, int amount, Connection con) throws Exception{
        String sql = "insert into orders(foodId,amount,orderTime) values(?,?,NOW())";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setInt(1, menuId);
        pstmt.setInt(2, amount);
        int num = pstmt.executeUpdate();
        if (num > 0) {
            return true;
        }
        return false;
    }
    //select orders.amount,menu.price from orders,menu WHERE orders.foodId = menu.id

    public int ordersSumTotal(Connection con) throws Exception{
        String sql = "select orders.amount,menu.price from orders,menu WHERE orders.foodId = menu.id";
        List<Order> listSumTotal = new ArrayList<Order>();
        PreparedStatement pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        int sumOrder=0;
        int sumOrders=0;
        // 处理结果集
        while (rs.next()) {
            Order order = new Order();
            int amount = rs.getInt("amount");
            int price = rs.getInt("price");
            sumOrder =amount*price;
            sumOrders+= sumOrder;
        }
        return sumOrders;
    }

    public boolean deleteorder(int id, Connection con) throws Exception {
        String sql = "delete from orders where orderId=?";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setInt(1, id);
        int num = pstmt.executeUpdate();
        if (num > 0) {
            return true;
        }
        return false;
    }
}
